package com.study.config;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.study.util.SqlScriptRunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class SystemConfig
{
    /**
     * 使用mysql数据库
     * 使用者不需关注数据库配置的初始化过程，本demo是借助jfinal框架初始化的数据库配置，
     * 使用者完全可以用其他方式代替
     */
    public static void initMysqlDruid()
    {
        C3p0Plugin c3p0Plugin = new C3p0Plugin("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai",
                "root", "test", "com.mysql.cj.jdbc.Driver", 1, 1, 1, 20, 1);
        c3p0Plugin.setDriverClass("com.mysql.cj.jdbc.Driver");
        c3p0Plugin.start();

        ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
        arp.setDialect(new MysqlDialect());
        arp.setDevMode(true);
        arp.setShowSql(true);
        arp.setContainerFactory(new CaseInsensitiveContainerFactory());
        arp.start();
    }

    /**
     * 表结构初始化
     */
    public static void initTableDesign()
    {
        Connection conn = null;
        try
        {
            conn = Db.use().getConfig().getConnection();
            File file = new File(System.getProperty("user.dir") + "/conf/sql");
            File[] files = file.listFiles();
            if (files.length == 0)
            {
                return;
            }
            List<File> fileList = Arrays.asList(file.listFiles());
            fileList.sort(Comparator.comparing(File::getName));
            for (File requestFile : fileList)
            {
                // 如下代码是读者需要关注的
                SqlScriptRunner runner = new SqlScriptRunner(conn);
                runner.setEscapeProcessing(false);
                runner.setSendFullScript(false);
                runner.setDelimiter(";;");
                runner.runScript(new InputStreamReader(new FileInputStream(requestFile), "UTF-8"));
            }
        }
        catch (Exception ex)
        {
            throw new RuntimeException("initTableDesign error!");
        }
        finally
        {
            Db.use().getConfig().close(conn);
        }
    }
}